package com.treeroot.planeservice.plane.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.treeroot.commonutils.exceptionhandler.MyException;
import com.treeroot.commonutils.ordervo.PlaneInfoOrder;
import com.treeroot.planeservice.plane.entity.PcPlane;

import com.treeroot.planeservice.plane.entity.PcPlaneConnecting;
import com.treeroot.planeservice.plane.entity.PcPlaneTransfer;
import com.treeroot.planeservice.plane.entity.vo.queryPlaneVo;
import com.treeroot.planeservice.plane.mapper.PcPlaneMapper;
import com.treeroot.planeservice.plane.service.PcPlaneConnectingService;
import com.treeroot.planeservice.plane.service.PcPlaneService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.treeroot.planeservice.plane.service.PcPlaneTransferService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author TreeRoot
 * @since 2022-04-20
 */
@Service
@Transactional //事务控制
public class PcPlaneServiceImpl extends ServiceImpl<PcPlaneMapper, PcPlane> implements PcPlaneService {

    @Autowired
    private PcPlaneTransferService planeTransferService;  //转程航班服务类
    @Autowired
    private PcPlaneConnectingService planeConnectingService;  //多程航班服务类



    /**
     * 查询所有,有或者没有航班的航班信息   flag =1 /0
     *
     * @param flag 有无航班信息
     * @return List<PcPlane> pcPlanes
     */

    @Override
    public List<PcPlane> getAllFlight(String flag) {
        //   根据 Wrapper 条件，查询全部记录 接入实体类，查询字段
        QueryWrapper<PcPlane> wrapper = new QueryWrapper<>();
        List<PcPlane> pcPlanes = baseMapper.selectList(wrapper);
        wrapper.eq("flag", flag);
        if (flag == null) {
            List<PcPlane> AllPlanes = baseMapper.selectList(wrapper);
            return AllPlanes;
        }
        return pcPlanes;
    }




    /** 远程调用
     * @param planeId
     * @param type    0未支付1已支付
     *
     */
    @Override
    public void myUpdate(String planeId, String type,String planeType) {

        if (type.equals("付款")) {
            if(planeType.equals("listBase")){
                baseMapper.updateSeatingByIdOrderReduce(planeId);//该机票剩余座位号-1

            } else if (planeType.equals("transfer")) {
                baseMapper.updateSeatingByIdOrderReduce2(planeId);//该机票剩余座位号-1

            }else if (planeType.equals("connecting")) {
                baseMapper.updateSeatingByIdOrderReduce3(planeId);//该机票剩余座位号-1

            }


        } else if (type.equals("退款")) {
            if(planeType.equals("listBase")){
                baseMapper.updateFlagByIdOrderAdd(planeId);//该机票剩余座位号+1

            } else if (planeType.equals("transfer")) {
                baseMapper.updateFlagByIdOrderAdd2(planeId);//该机票剩余座位号+1

            }else if (planeType.equals("connecting")) {
                baseMapper.updateFlagByIdOrderAdd3(planeId);//该机票剩余座位号+1

            }
        } else throw new MyException(2000, "没想到操作");


    }
    //TODO:设置往返程，先查出本次可出发的机票，在选定本次可出发的机票后 再去展示第二张返程的机票信息即 目的地为出发地  出发地为目的地
    //TODO:做redis请求缓存

    /**
     *  航班条件条件分页查询
     * @param type  查询类型
     * @param current  当前页
     * @param limit  最大页
     * @param query   查询条件
     * @return
     */
    @Override
    public Map getPlaneMessage(String type, long current, long limit,queryPlaneVo query) {

        boolean listBaseFlag = type.equals("listBase");
        boolean transferFlag = type.equals("transfer");
        boolean connectingFlag = type.equals("connecting");


        if(listBaseFlag) {

            Page<PcPlane> pagePlane = new Page<>(current, limit);

            //      构建实体类
            PcPlane plane = new PcPlane();
            plane.setFlightNumber(query.getFlightNumber());
            plane.setStartDateTime(query.getStartDateTime());
            plane.setStartCity(query.getStartCity());
            plane.setEndCity(query.getEndCity());

            LambdaQueryWrapper<PcPlane> wrapper = new QueryWrapper<PcPlane>().lambda()

                    .between(PcPlane::getPrice, query.getPriceStart(), query.getPriceEnd())
                    //    出发日期(startDateTime)、航班号（flightNumber） 查询
                    .eq(  //根据航班号（flightNumber），出发日期（startDateTime）查询
                            !StringUtils.isEmpty(plane.getFlightNumber()),
                            PcPlane::getFlightNumber,
                            plane.getFlightNumber()
                    )
                    .or(i -> i.eq(
                                    !StringUtils.isEmpty(plane.getStartDateTime()),
                                    PcPlane::getStartDateTime,
                                    plane.getStartDateTime()
                            )
                    ).eq(
                            !StringUtils.isEmpty(plane.getStartDateTime()),
                            PcPlane::getStartDateTime,
                            plane.getStartDateTime()
                    )
                    //    出发日期(startDateTime)，出发地(startCity)、目的地(endCity) 查询
                    .or(i -> i.eq
                                    (!StringUtils.isEmpty(plane.getStartDateTime()),
                                            PcPlane::getStartDateTime,
                                            plane.getStartDateTime()

                                    ).eq(!StringUtils.isEmpty(plane.getStartCity()),
                                    PcPlane::getStartCity,
                                    plane.getStartCity()
                            ).eq(!StringUtils.isEmpty(plane.getEndCity()),
                                    PcPlane::getEndCity,
                                    plane.getEndCity())
                    );
            //    调用方法实现查询
            baseMapper.selectPage(pagePlane, wrapper);
            long total = pagePlane.getTotal();//总记录数
            List<PcPlane> records = pagePlane.getRecords();//数据list集合
            Map map = new HashMap();
            map.put(" total", total);
            map.put("rows", records);
            return map;
        }
        else if (transferFlag) {


                //      创建一个Page对象

                Page<PcPlaneTransfer> pagePlane = new Page<>(current, limit);
                //      构建实体类
                PcPlaneTransfer plane = new PcPlaneTransfer();
                plane.setFlightNumber(query.getFlightNumber());
                plane.setStartDateTime(query.getStartDateTime());
                plane.setStartCity(query.getStartCity());
                plane.setEndCity(query.getEndCity());

                LambdaQueryWrapper<PcPlaneTransfer> wrapper = new QueryWrapper<PcPlaneTransfer>().lambda()
                        // 以价格区间来查询航班
                        .between(PcPlaneTransfer::getPrice, query.getPriceStart(), query.getPriceEnd())
                        //    出发日期(startDateTime)、航班号（flightNumber） 查询
                        .eq(
                                !StringUtils.isEmpty(plane.getFlightNumber()),
                                PcPlaneTransfer::getFlightNumber,
                                plane.getFlightNumber()
                        )

                        .or(i -> i.eq(
                                !StringUtils.isEmpty(plane.getStartDateTime()),
                                PcPlaneTransfer::getStartDateTime,
                                plane.getStartDateTime()
                        ))
                        .eq(
                                !StringUtils.isEmpty(plane.getStartDateTime()),
                                PcPlaneTransfer::getStartDateTime,
                                plane.getStartDateTime()
                        )
                        //    出发日期(startDateTime)，出发地(startCity)、目的地(endCity) 查询
                        .or(i -> i.eq
                                        (!StringUtils.isEmpty(plane.getStartDateTime()),
                                                PcPlaneTransfer::getStartDateTime,
                                                plane.getStartDateTime()

                                        ).eq(!StringUtils.isEmpty(plane.getStartCity()),
                                        PcPlaneTransfer::getStartCity,
                                        plane.getStartCity()
                                ).eq(!StringUtils.isEmpty(plane.getEndCity()),
                                        PcPlaneTransfer::getEndCity,
                                        plane.getEndCity())
                        );
                //    调用方法实现查询
                planeTransferService.page(pagePlane, wrapper);
                long total = pagePlane.getTotal();//总记录数
                List<PcPlaneTransfer> records = pagePlane.getRecords();//数据list集合
            Map map = new HashMap();
            map.put(" total", total);
            map.put("rows", records);
            return map;

            }
        else if (connectingFlag) {

            Page<PcPlaneConnecting> pagePlane = new Page<>(current, limit);
            //      构建实体类
            PcPlaneConnecting plane = new PcPlaneConnecting();
            plane.setFlightNumber(query.getFlightNumber());
            plane.setStartDateTime(query.getStartDateTime());
            plane.setStartCity(query.getStartCity());
            plane.setEndCity(query.getEndCity());

            LambdaQueryWrapper<PcPlaneConnecting> wrapper = new QueryWrapper<PcPlaneConnecting>().lambda()
                    .between(PcPlaneConnecting::getPrice, query.getPriceStart(), query.getPriceEnd())
                    //    出发日期(startDateTime)、航班号（flightNumber） 查询
                    .eq(
                            !StringUtils.isEmpty(plane.getFlightNumber()),
                            PcPlaneConnecting::getFlightNumber,
                            plane.getFlightNumber()
                    )

                    .or(i -> i.eq(
                            !StringUtils.isEmpty(plane.getStartDateTime()),
                            PcPlaneConnecting::getStartDateTime,
                            plane.getStartDateTime()
                    ))

                    .eq(
                            !StringUtils.isEmpty(plane.getStartDateTime()),
                            PcPlaneConnecting::getStartDateTime,
                            plane.getStartDateTime()
                    )
                    //    出发日期(startDateTime)，出发地(startCity)、目的地(endCity) 查询
                    .or(i -> i.eq
                                    (!StringUtils.isEmpty(plane.getStartDateTime()),
                                            PcPlaneConnecting::getStartDateTime,
                                            plane.getStartDateTime()

                                    ).eq(!StringUtils.isEmpty(plane.getStartCity()),
                                    PcPlaneConnecting::getStartCity,
                                    plane.getStartCity()
                            ).eq(!StringUtils.isEmpty(plane.getEndCity()),
                                    PcPlaneConnecting::getEndCity,
                                    plane.getEndCity())
                    );
            //    调用方法实现查询
            planeConnectingService.page(pagePlane, wrapper);
            long total = pagePlane.getTotal();//总记录数
            List<PcPlaneConnecting> records = pagePlane.getRecords();//数据list集合
            Map map = new HashMap();
            map.put(" total", total);
            map.put("rows", records);
            return map;
        }
        else {
            Map map = new HashMap<>();
            map.put(20000, "错误执行");
            return map;
        }


    }

    /**
     * 【远程调用】根据航班id查询航班信息
     *
     * @param id 航班号的id
     */
    @Override
    public PlaneInfoOrder getOrderInfo(String id,String planeType) {

//        返回来的类型是是普通航班
        if (planeType.equals("listBase")){
            PcPlane plane = baseMapper.selectById(id);
            PlaneInfoOrder planeInfoOrder = new PlaneInfoOrder();
            BeanUtils.copyProperties(plane, planeInfoOrder);
            return planeInfoOrder;
        }
        //        返回来的类型是是转程航班
        else if (planeType.equals("transfer")) {

            PcPlaneTransfer plane = planeTransferService.getById(id);
            PlaneInfoOrder planeInfoOrder = new PlaneInfoOrder();
            BeanUtils.copyProperties(plane, planeInfoOrder);
            return planeInfoOrder;

            //        返回来的类型是是多程航班
        } else if (planeType.equals("connecting")) {
            PcPlaneConnecting plane = planeConnectingService.getById(id);
            PlaneInfoOrder planeInfoOrder = new PlaneInfoOrder();
            BeanUtils.copyProperties(plane, planeInfoOrder);
            return planeInfoOrder;
        }


        return null;
    }

    /**
     * 分页
     *
     * @param current 当前页
     * @param limit   最大页
     * @return
     */
    @Override
    public Map getPageList(long current, long limit) {

        Page<PcPlane> page =new Page<>(current,limit);
        baseMapper.selectPage(page,null);
        List<PcPlane> records = page.getRecords();
        long total = page.getTotal();
        Map map =new HashMap();
        map.put("total",total);
        map.put("rows",records);
       return map;
    }

    /**
     * 【后台】航班条件分页
     * @param current
     * @param limit
     * @param plane
     * @return
     */
    @Override
    public Map getQueryPageList(long current, long limit, PcPlane plane) {

        Page<PcPlane> planePage =new Page<>(current,limit);
        //调用方法的时候，底层封装把分页所有数据封装到pagePlane对象里
        LambdaQueryWrapper<PcPlane> wrapper = new QueryWrapper<PcPlane>().lambda()


                .eq(  //根据航班号（flightNumber），出发日期（startDateTime）查询
                        !StringUtils.isEmpty(plane.getFlightNumber()),
                        PcPlane::getFlightNumber,
                        plane.getFlightNumber()
                )
                .or(i -> i.eq(
                                !StringUtils.isEmpty(plane.getStartDateTime()),
                                PcPlane::getStartDateTime,
                                plane.getStartDateTime()
                        )
                )

                .eq(//    出发日期(startDateTime)，出发地(startCity)、目的地(endCity) 查询
                        !StringUtils.isEmpty(plane.getStartDateTime()),
                        PcPlane::getStartDateTime,
                        plane.getStartDateTime()
                )
                .or(i -> i.eq
                                (!StringUtils.isEmpty(plane.getStartDateTime()),
                                        PcPlane::getStartDateTime,
                                        plane.getStartDateTime()

                                ).eq(!StringUtils.isEmpty(plane.getStartCity()),
                                PcPlane::getStartCity,
                                plane.getStartCity()
                        ).eq(!StringUtils.isEmpty(plane.getEndCity()),
                                PcPlane::getEndCity,
                                plane.getEndCity())
                );


        //    调用方法实现查询
        baseMapper.selectPage(planePage, wrapper);
        long total = planePage.getTotal();
        List<PcPlane> records = planePage.getRecords();
        Map map =new HashMap();
        map.put("total",total);
        map.put("rows",records);
        return map;
    }
}


    /**
     * 通过 出发日期(startDateTime)、航班号（flightNumber），或者 出发日期(startDateTime)，出发地(startCity)、目的地(endCity)
     * <p>
     * <p>
     * 查询到 含航班的起（flightStartTime）降（flightEndTime）时间  剩余座位数（seating）  票价（price）
     *
     * @param sdt 出发日期(startDateTime)
     * @param fn  航班号（flightNumber）
     * @param sc  出发地(startCity)
     * @param ec  目的地(endCity)
     * @return List<PcPlane> pcPlanes
     */

//    @Override
//    public List<PcPlane> getPlaneInfo(String sdt, String fn, String sc, String ec) {
//        //    出发日期(startDateTime)、航班号（flightNumber） 查询
//        QueryWrapper<PcPlane> wrapper = new QueryWrapper<>();
//        wrapper.select("flight_start_time", "flight_end_time", "seating", "price")
//
//                .eq("start_date_time", sdt).eq("flight_number", fn)
//
//                //        出发日期(startDateTime)，出发地(startCity)、目的地(endCity) 查询
//                .or(i -> i.eq("start_date_time", sdt).eq("start_city", sc).eq("end_city", ec))
//
//                //        综合随便查询
//                .or(i -> i.eq("start_date_time", sdt).or().eq("start_city", sc).or().eq("end_city", ec).or().eq("flight_number", fn));
//
//        List<PcPlane> listBase = baseMapper.selectList(wrapper);
//
//
//        return listBase;
//
//
//    }



